<?php

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class Member extends Model
{
    use SoftDelete;
    protected $readonly = ['username', 'email'];

    public function add($data)
    {
        $validate = new \app\common\validate\Member();
        if (!$validate->scene('add')->check($data)) {
            return $validate->getError();
        }
        $data['nickname'] = $data['username'];
        $result = $this->allowField(true)->save($data);
        if ($result) {
            return 1;
        }else {
            return '会员添加失败！';
        }
    }

    public function edit($data)
    {
        $validate = new \app\common\validate\Member();
        if (!$validate->scene('edit')->check($data)) {
            return $validate->getError();
        }
        $memberInfo = $this->find($data['id']);
        if ($data['oldpass'] != $memberInfo['password']) {
            return '原密码不正确！';
        }
        $memberInfo->password = $data['newpass'];
        $memberInfo->nickname = $data['nickname'];
        $result = $memberInfo->save();
        if ($result) {
            return 1;
        }else {
            return '信息修改失败！';
        }
    }

    public function register($data)
    {
        $validate = new \app\common\validate\Member();
        if (!$validate->scene('register')->check($data)) {
            return $validate->getError();
        }
        $data['nickname'] = $data['username'];
        $result = $this->allowField(true)->save($data);
        if ($result) {
            $user = [
                'id' => $this->id,
                'nickname' => $data['nickname']
            ];
            session('index', $user);
            return 1;
        }else {
            return '注册失败！';
        }
    }
}
